const baseURL = 'http://192.168.0.103:28089';

const Ajax = ({
    url = "",
    method = "get",
    param = {},
    sessionId,
} = {}) => {
    return new Promise((resolve, reject) => {
        if(method === "upload") {
            wx.uploadFile({
                url: getUrl(url),
                filePath: param.filePath,
                name: 'file',
                header: { 
                    sessionId,
                },
                success: res => {
                    resolve(res.data)
                },
                fail: err => {
                    reject(err)
                }
    
            })
        } else {
            wx.request({
                url: getUrl(url),
                header: {
                    sessionId,
                },
                data: param,
                method,
                success: res => {
                    resolve(res.data)
                },
                fail: err => {
                    reject(err)
                }
            })
        }
        
    })
}

const getUrl = (url) => {
    if (url.indexOf('://') == -1) {
        url = baseURL + url;
    }
    return url;
}

const get = (url, param, sessionId) => {
    return Ajax({
        url,
        param,
        sessionId
    })
}

const post = (url, param, sessionId) => {
    return Ajax({
        url,
        method: 'post',
        param,
        sessionId,
    })
}

const _delete = (url, param, sessionId) => {
    return Ajax({
        url,
        method: 'delete',
        param,
        sessionId,
    })
}

const upload = (url, param, sessionId) => {
    return Ajax({
        url,
        method: "upload",
        param,
        sessionId,
    })
}

module.exports = {
    baseURL,
    get,
    post,
    upload,
    _delete
}